package com.stonedt.spider.controller.datasource;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stonedt.spider.entity.SpiderFlow;
import com.stonedt.spider.entity.SpiderFlowDataSource;
import com.stonedt.spider.scheduled.SpiderJob;
import com.stonedt.spider.scheduled.SpiderJobManager;
import com.stonedt.spider.service.SpiderFlowDataSourceService;
import com.stonedt.spider.service.SpiderFlowService;
import com.stonedt.spider.service.WebSiteTypeService;
import com.stonedt.spider.util.DateUtil;
import com.stonedt.spider.util.MongodbTestSpiderflow;
import com.stonedt.spider.util.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/spiderflow")
public class SpiderFlowController {

    private static Logger logger = Logger.getLogger(SpiderFlowController.class);

    @Autowired
    SpiderFlowService spiderFlowService;

    @Autowired
    private WebSiteTypeService webSiteTypeService;

    @Autowired
    private SpiderFlowDataSourceService dataSourceService;
    
    @Autowired
    private SpiderJobManager spiderJobManager;

    /***
     * 璇︽儏椤甸潰
     * @param
     * @return
     */
    @RequestMapping(value = "/spiderlist/{website_id}/{pageNo}/{pageSize}")
    @ResponseBody
    public ResultUtil spiderlist(@PathVariable Integer website_id, @PathVariable Integer pageNo, @PathVariable Integer pageSize) {
        ResultUtil resultUtil = new ResultUtil();
        PageHelper.startPage(pageNo, pageSize);
        List<SpiderFlow> spiderFlows = spiderFlowService.searchSpiderFlows(website_id,pageNo,pageSize);
        PageInfo<SpiderFlow> pageInfo = new PageInfo<SpiderFlow>(spiderFlows);
        Map map = new HashMap();
        map.put("website_id",website_id.toString());
        Integer count = MongodbTestSpiderflow.searchCount(map, null);
        pageInfo.setTotal(count);
        pageInfo.setPageSize(pageSize);
        int pages = count % pageSize == 0 ? count/pageSize : count/pageSize +1;
        pageInfo.setPages(pages);
        resultUtil.setStatus(200);
        resultUtil.setData(pageInfo);
        return resultUtil;
    }
    
    /***
     * bid列表
     * @param
     * @return
     */
    @RequestMapping(value = "/spiderBidlist/{website_id}/{pageNo}/{pageSize}")
    @ResponseBody
    public ResultUtil spiderBidlist(@PathVariable Integer website_id, @PathVariable Integer pageNo, @PathVariable Integer pageSize) {
        ResultUtil resultUtil = new ResultUtil();
        PageHelper.startPage(pageNo, pageSize);
        List<SpiderFlow> spiderFlows = spiderFlowService.searchBidSpiderFlows(website_id,pageNo,pageSize);
        PageInfo<SpiderFlow> pageInfo = new PageInfo<SpiderFlow>(spiderFlows);
        Map map = new HashMap();
        map.put("website_id",website_id.toString());
        Integer count = MongodbTestSpiderflow.searchCount(map, null);
        pageInfo.setTotal(count);
        pageInfo.setPageSize(pageSize);
        int pages = count % pageSize == 0 ? count/pageSize : count/pageSize +1;
        pageInfo.setPages(pages);
        resultUtil.setStatus(200);
        resultUtil.setData(pageInfo);
        return resultUtil;
    }


    /***
     * 璇︽儏椤甸潰
     * @param
     * @return
     */
    @RequestMapping(value = "/detail/{id}")
    @ResponseBody
    public ModelAndView detail(@PathVariable Integer id, ModelAndView mv) {
        //
        mv.setViewName("spiderflow/editor");
        mv.addObject("url", fileRead());
        mv.addObject("id", id.toString());
        mv.addObject("websiteId", "");
        return mv;

    }
    
    /***
     * 璇︽儏椤甸潰
     * @param
     * @return
     */
    @RequestMapping(value = "/BiDdetail/{id}")
    @ResponseBody
    public ModelAndView BiDdetail(@PathVariable Integer id, ModelAndView mv) {
        //
        mv.setViewName("spiderflow/bid_editor");
        mv.addObject("url", fileRead());
        mv.addObject("id", id.toString());
        mv.addObject("websiteId", "");
        return mv;

    }

    @RequestMapping(value = "/saveSkip")
    @ResponseBody
    public ModelAndView saveSkip(@RequestParam Integer websiteId, ModelAndView mv) {
        //
        mv.setViewName("spiderflow/editor");
        mv.addObject("url", fileRead());
        mv.addObject("id", "");
        mv.addObject("websiteId", websiteId.toString());
        return mv;

    }
    
    @RequestMapping(value = "/saveBidSkip")
    @ResponseBody
    public ModelAndView saveBidSkip(@RequestParam Integer websiteId, ModelAndView mv) {
        //
        mv.setViewName("spiderflow/bid_editor");
        mv.addObject("url", fileRead());
        mv.addObject("id", "");
        mv.addObject("websiteId", websiteId.toString());
        return mv;

    }

    /**
     * 鑾峰彇鐖櫕xml
     *
     * @param id
     * @return
     */
    @RequestMapping("/xml")
    @ResponseBody
    public ResultUtil getXml(@RequestParam int id) {
        SpiderFlow flow = spiderFlowService.searchSpiderFlow(id);
        ResultUtil resultUtil = new ResultUtil();
        if (flow != null) {
            JSONObject param = new JSONObject();
            param.put("source_name", flow.getWebsite_name());
            param.put("sourcewebsitename", flow.getWebsite_name());
            param.put("extend_string_five", flow.getSeed_name());
            param.put("bloomName", flow.getBloomname());
//            param.put("bloomName", "BLOOM_INFOS_TEST123");
            param.put("websitelogo", flow.getWebsite_ico());
            param.put("otherwebsiteid", flow.getWebsite_id());
            param.put("website_id", flow.getWebsite_id());
            param.put("seed_id", flow.getId());
            param.put("es_type", flow.getEstype());
            param.put("es_index", flow.getEsindex());
            param.put("hbase_table", flow.getHbase_table());
            param.put("kafka_queue_name", flow.getKafka_queue_name());
            param.put("sendDate", DateUtil.getDate());
            //鑾峰彇鏈嶅姟鍣╥p
            param.put("sendIp", SpiderJob.getLocalIP());
            param.put("sendPort", SpiderJob.getLocalPort());

            Integer new_website_type = flow.getNew_website_type();
            if (new_website_type == null) {
                new_website_type = 8;
            }
            param.put("classify", new_website_type);
            param.put("similarvolume", 1);
            double a = Math.random() * 100;
            DecimalFormat df = new DecimalFormat("0.00");
            param.put("heatvolume", df.format(a));

            Map map = new HashMap();
            map.put("xml", flow.getXml());
            //杞垚json瀛楃涓�
            String json = param.toJSONString();
            //鍔犲瘑
            map.put("json", SpiderJob.compress(json));
            map.put("spiderFlow", flow);
            resultUtil.setStatus(200);
            resultUtil.setData(map);
        }
        return resultUtil;
    }
    
    /**
     * 鑾峰彇鐖櫕xml-招投标
     *
     * @param id
     * @return
     */
    @RequestMapping("/bid_xml")
    @ResponseBody
    public ResultUtil getBidXml(@RequestParam int id) {
        SpiderFlow flow = spiderFlowService.searchBidSpiderFlow(id);
        ResultUtil resultUtil = new ResultUtil();
        if (flow != null) {
            JSONObject param = new JSONObject();
            param.put("source_name", flow.getWebsite_name());
            param.put("sourcewebsitename", flow.getWebsite_name());
            param.put("extend_string_five", flow.getSeed_name());
            param.put("bloomName", flow.getBloomname());
//            param.put("bloomName", "BLOOM_INFOS_TEST123");
            param.put("websitelogo", flow.getWebsite_ico());
            param.put("otherwebsiteid", flow.getWebsite_id());
            param.put("website_id", flow.getWebsite_id());
            param.put("seed_id", flow.getId());
            param.put("es_type", flow.getEstype());
            param.put("es_index", flow.getEsindex());
            param.put("hbase_table", flow.getHbase_table());
            param.put("kafka_queue_name", flow.getKafka_queue_name());
            param.put("sendDate", DateUtil.getDate());
            //鑾峰彇鏈嶅姟鍣╥p
            param.put("sendIp", SpiderJob.getLocalIP());
            param.put("sendPort", SpiderJob.getLocalPort());

            Integer new_website_type = flow.getNew_website_type();
            if (new_website_type == null) {
                new_website_type = 8;
            }
            param.put("classify", new_website_type);
            param.put("similarvolume", 1);
            double a = Math.random() * 100;
            DecimalFormat df = new DecimalFormat("0.00");
            param.put("heatvolume", df.format(a));

            Map map = new HashMap();
            map.put("xml", flow.getXml());
            //杞垚json瀛楃涓�
            String json = param.toJSONString();
            //鍔犲瘑
            map.put("json", SpiderJob.compress(json));
            map.put("spiderFlow", flow);
            resultUtil.setStatus(200);
            resultUtil.setData(map);
        }
        return resultUtil;
    }


    public static String fileRead() {

        // 鑾峰彇绯荤粺鐜鍙橀噺
        String getenv = System.getenv("PROPERTIES_SPIDER");
        // 濡傛灉寮�鍙戞椂娌℃湁绯荤粺鐜鍙橀噺 浣跨敤鑷繁鑷畾涔変竴涓矾寰�
        String path = "";
        if (null == getenv) {
            path = "D:\\env";
//            path = "/opt/properties-spider";
        } else {
            path = getenv.replace('\\', '/');
        }
        try {
            BufferedReader systemBr = new BufferedReader(
                    new InputStreamReader(new FileInputStream(new File(path + "/config/spider.properties")), "utf-8"));
            String SystemLine = null;
            String readline = "";
            while ((SystemLine = systemBr.readLine()) != null) {
                if (!SystemLine.trim().startsWith("#")) {
                    String[] split = SystemLine.split("=");

                    for (int i = 1; i < split.length; i++) {
                        if (i < split.length - 1) {
                            readline += split[i] + "=";
                        } else {
                            readline += split[i];
                        }
                    }
                    if (split[0].equals("spiderFlow")) {
                        systemBr.close();

//                        readline = "http://192.168.71.83:8383/";
                        logger.info("璇诲彇鎴愬姛,url=" + readline);
                        return readline;
                    }
                    readline = "";
                }
            }
            systemBr.close();

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("spiderFlow璺緞璇诲彇澶辫触" + e.getMessage());
        }
        logger.error("spiderFlow璺緞璇诲彇澶辫触,娌℃湁鎵剧殑瀵瑰簲閰嶇疆");
        return "";
    }


    /**
     * @return
     * @throws
     * @author dxk
     * @date 2021/4/15 9:55
     * 淇濆瓨鐖櫕xml
     * @since
     */
    @RequestMapping("/save")
    @ResponseBody
    public ResultUtil spiderSave(SpiderFlow spiderFlow) {
//        Map<String, Map<Integer, Map<String, Object>>> spiderList = SpiderJobManager.spiderList;
//    	SpiderJobManager
//        if (spiderList != null && StringUtils.isNotBlank(spiderFlow.getCron())) {
//            Map<Integer, Map<String, Object>> integerMapMap = spiderList.get(spiderFlow.getCron());
//            if (integerMapMap != null && spiderFlow.getId() != null) {
//                Map<String, Object> map = integerMapMap.get(spiderFlow.getId());
//                if (map != null) {
//                    System.out.println("before_________:" + JSONObject.toJSONString(map));
//                    Object xml = map.get("xml");
//                    System.out.println("before_____xml__________:" + xml);
//                }
//
//            }
//        }


        //鏍规嵁鍞竴鏍囪瘑鏌ヨ
        if (spiderFlow.getId() != null) {
//            spiderList = SpiderJobManager.spiderList;
//            if (spiderList != null) {
//                SpiderFlow spiderFlow1 = spiderFlowService.searchSpiderFlow(spiderFlow.getId());
//                String cron = spiderFlow1.getCron();
//                Map<Integer, Map<String, Object>> integerMapMap1 = spiderList.get(cron);
//                if (integerMapMap1 != null) {
//                    Map<String, Object> map = integerMapMap1.get(spiderFlow.getId());
//                    if (map != null) {
//                        System.out.println("oldxml_________--" + JSONObject.toJSONString(map));
//                    }
//                }
//            }
//            //淇敼涔嬪墠鍒犻櫎鍐呭瓨涓殑鍘熼厤缃�
//            spiderFlowService.deleteSpiderFlowJob(spiderFlow);
//            //淇敼
//            
        	spiderFlowService.updateSpiderFlowById(spiderFlow);
        } else {
            spiderFlowService.insertSpiderFlow(spiderFlow);
            Integer seed_status = spiderFlow.getSeed_status();
            if(null != seed_status && 1== seed_status){
            	List<String> cronList = SpiderJobManager.cronList;
                String cron = spiderFlow.getCron();
                if(StringUtils.isNotBlank(cron)){
                	cron = cron.trim();
                	boolean flag = true;
                	for (int i = 0; i < cronList.size(); i++) {
                		if(cron.equals(cronList.get(i))){
                			flag = false;
                			break;
                		}
                	}
                	if(flag){
                		spiderJobManager.addJob(cron);
                	}
                }
            }
        }

//        //娣诲姞瀹氭椂浠诲姟
//        spiderFlowService.statusSpiderFlowJob(spiderFlow);
//        spiderList = SpiderJobManager.spiderList;
//        if (spiderList != null && StringUtils.isNotBlank(spiderFlow.getCron())) {
//            Map<Integer, Map<String, Object>> integerMapMap = spiderList.get(spiderFlow.getCron());
//            if (integerMapMap != null && spiderFlow.getId() != null) {
//                Map<String, Object> map = integerMapMap.get(spiderFlow.getId());
//                if (map != null) {
//                    System.out.println("after_________:" + JSONObject.toJSONString(map));
//                    Object xml = map.get("xml");
//                    System.out.println("after_____xml__________:" + xml);
//                }
//
//            }
//        }
        return new ResultUtil(spiderFlow.getId());
    }
    
    /**
     * @return
     * @throws
     * @author dxk
     * @date 2021/4/15 9:55
     * 淇濆瓨鐖櫕xml
     * @since
     */
    @RequestMapping("/spiderBidSave")
    @ResponseBody
    public ResultUtil spiderBidSave(SpiderFlow spiderFlow) {

        if (spiderFlow.getId() != null) {        
        	spiderFlowService.updateBidSpiderFlowById(spiderFlow);
        } else {
            spiderFlowService.insertBidSpiderFlow(spiderFlow);
            Integer seed_status = spiderFlow.getSeed_status();
            if(null != seed_status && 1== seed_status){
            	List<String> cronList = SpiderJobManager.cronList;
                String cron = spiderFlow.getCron();
                if(StringUtils.isNotBlank(cron)){
                	cron = cron.trim();
                	boolean flag = true;
                	for (int i = 0; i < cronList.size(); i++) {
                		if(cron.equals(cronList.get(i))){
                			flag = false;
                			break;
                		}
                	}
                	if(flag){
                		spiderJobManager.addJob(cron);
                	}
                }
            }
        }

        return new ResultUtil(spiderFlow.getId());
    }

//    @RequestMapping("/searchSpiderFlowList")
//    @ResponseBody
//    public String SpdierFlowJobList() {
//        Map<String, Map<Integer, Map<String, Object>>> spiderList = SpiderJobManager.spiderList;
//        Set<String> keySet = spiderList.keySet();
//        JSONObject reault = new JSONObject();
//        int size = keySet.size();
//        reault.put("size", size);
//        JSONArray jsonArray = new JSONArray();
//        for (String key : keySet) {
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put(key, spiderList.get(key).keySet().size());
//            jsonArray.add(jsonObject);
//        }
//        reault.put("list", jsonArray);
//        return reault.toJSONString();
//    }


//    @RequestMapping("/searchSpiderFlowDetail")
//    @ResponseBody
//    public String SpdierFlowJobDetail(@RequestParam String cron) {
//        Map<String, Map<Integer, Map<String, Object>>> spiderList = SpiderJobManager.spiderList;
//        Map<Integer, Map<String, Object>> map = spiderList.get(cron);
//        JSONObject reault = new JSONObject();
//
//        Set<Integer> keySet = map.keySet();
//        reault.put("size", keySet.size());
//        JSONArray jsonArray = new JSONArray();
//        for (Integer key : keySet) {
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("id", key);
//            jsonObject.put("param", JSON.toJSONString(map.get(key)));
//            jsonArray.add(jsonObject);
//        }
//        reault.put("list", jsonArray);
//        return reault.toJSONString();
//    }

    /**
     * @return
     * @throws
     * @author dxk
     * @date 2021/4/15 18:02
     * 鑾峰彇琛ㄨ揪寮忔渶杩戜簲娆¤繍琛屾椂闂�
     * @since
     */
    @RequestMapping("/recent5TriggerTime")
    @ResponseBody
    public List<String> getRecent5TriggerTime(@RequestParam String cron) {
        return spiderFlowService.getRecentTriggerTime(cron, 5);
    }

    /**
     * @return
     * @throws
     * @author dxk
     * @date 2021/4/15 11:24
     * 鏌ヨ鎵�鏈夌殑鏁版嵁绫诲瀷    id  typename 瀛楁
     * @since
     */
    @RequestMapping("/websitetype")
    @ResponseBody
    public ResultUtil websitetype() {
        List<Map<String, Object>> list = webSiteTypeService.selectList();
        return new ResultUtil(list);
    }
    
    /**
     * 查询招投标数据类型 id
     * @since
     */
    @RequestMapping("/bidWebsitetype")
    @ResponseBody
    public ResultUtil bidWebsitetype() {
        List<Map<String, Object>> list = webSiteTypeService.selectBidList();
        return new ResultUtil(list);
    }

    /**
     * @return
     * @throws
     * @author dxk
     * @date 2021/4/19 10:19
     * 淇敼鐖櫕鐘舵��,鍚屾椂鎿嶄綔瀹氭椂浠诲姟鐨勫唴瀛�
     * @since
     */
    @RequestMapping("/updateSpiderStatus")
    @ResponseBody
    public ResultUtil updateSpiderStatus(SpiderFlow spiderFlow) {

        int flag = spiderFlowService.updateSpiderFlowById(spiderFlow);

        //鏍规嵁鐘舵�佷慨鏀瑰畾鏃朵换鍔�
//        spiderFlowService.statusSpiderFlowJob(spiderFlow);


        return new ResultUtil(spiderFlow.getId());
    }
    
    /**
     * 修改状态-招投标
     * @since
     */
    @RequestMapping("/updateBidSpiderStatus")
    @ResponseBody
    public ResultUtil updateBidSpiderStatus(SpiderFlow spiderFlow) {

        int flag = spiderFlowService.updateBidSpiderFlowById(spiderFlow);


        return new ResultUtil(spiderFlow.getId());
    }


    /**
     * @return
     * @throws
     * @author dxk
     * @date 2021/5/6 14:01
     * 鏌ヨspiderflow閰嶇疆鐨勬暟鎹簮
     * @since
     */
    @RequestMapping("/all")
    @ResponseBody
    public List<SpiderFlowDataSource> all() {

        return dataSourceService.selectListAll();
    }

    /**
     * @return
     * @throws
     * @author dxk
     * @date 2021/5/18 15:51
     * 鏍规嵁鏁版嵁绫诲瀷鑾峰彇娴嬭瘯闇�瑕佺殑json
     * @since
     */
    @RequestMapping("/getTypeJson")
    @ResponseBody
    public ResultUtil getTypeJson(@RequestParam("typeid") int typeid, @RequestParam("websiteId") int websiteId,
                                  @RequestParam("seed_name") String seed_name, @RequestParam("id") Integer id) {
        Map<String, Object> map = spiderFlowService.getTypeJson(typeid, websiteId);
        JSONObject param = new JSONObject();
        param.put("source_name", map.get("website_name"));
        param.put("sourcewebsitename", map.get("website_name"));
        param.put("extend_string_five", seed_name);
        param.put("bloomName", map.get("bloomname"));
        param.put("websitelogo", map.get("website_ico"));
        param.put("otherwebsiteid", websiteId);
        param.put("website_id", websiteId);
        if (id != null) {
            param.put("seed_id", id);
        } else {
            param.put("seed_id", "test");
        }

        param.put("es_type", map.get("estype"));
        param.put("es_index", map.get("esindex"));
        param.put("hbase_table", map.get("hbase_table"));
        param.put("kafka_queue_name", map.get("kafka_queue_name"));
        param.put("sendDate", DateUtil.getDate());
        //鑾峰彇鏈嶅姟鍣╥p
        param.put("sendIp", SpiderJob.getLocalIP());
        param.put("sendPort", SpiderJob.getLocalPort());
        Object new_website_type = map.get("new_website_type");
        if (new_website_type == null) {
            new_website_type = 8;
        }
        param.put("classify", new_website_type);
        param.put("similarvolume", 1);
        double a = Math.random() * 100;
        DecimalFormat df = new DecimalFormat("0.00");
        param.put("heatvolume", df.format(a));

        String compress = SpiderJob.compress(param.toJSONString());
        ResultUtil resultUtil = new ResultUtil();
        resultUtil.setData(compress);
        resultUtil.setStatus(200);
        return resultUtil;
    }

    /**
     * @since
     */
    @RequestMapping("/getBidTypeJson")
    @ResponseBody
    public ResultUtil getBidTypeJson(@RequestParam("typeid") int typeid, @RequestParam("websiteId") int websiteId,
                                  @RequestParam("seed_name") String seed_name, @RequestParam("id") Integer id) {
        Map<String, Object> map = spiderFlowService.getBidTypeJson(typeid, websiteId);
        JSONObject param = new JSONObject();
        param.put("source_name", map.get("website_name"));
        param.put("sourcewebsitename", map.get("website_name"));
        param.put("extend_string_five", seed_name);
        param.put("bloomName", map.get("bloomname"));
        param.put("websitelogo", map.get("website_ico"));
        param.put("otherwebsiteid", websiteId);
        param.put("website_id", websiteId);
        if (id != null) {
            param.put("seed_id", id);
        } else {
            param.put("seed_id", "test");
        }

        param.put("es_type", map.get("estype"));
        param.put("es_index", map.get("esindex"));
        param.put("hbase_table", map.get("hbase_table"));
        param.put("kafka_queue_name", map.get("kafka_queue_name"));
        param.put("sendDate", DateUtil.getDate());
        //鑾峰彇鏈嶅姟鍣╥p
        param.put("sendIp", SpiderJob.getLocalIP());
        param.put("sendPort", SpiderJob.getLocalPort());
        Object new_website_type = map.get("new_website_type");
        if (new_website_type == null) {
            new_website_type = 8;
        }
        param.put("classify", new_website_type);
        param.put("similarvolume", 1);
        double a = Math.random() * 100;
        DecimalFormat df = new DecimalFormat("0.00");
        param.put("heatvolume", df.format(a));

        String compress = SpiderJob.compress(param.toJSONString());
        ResultUtil resultUtil = new ResultUtil();
        resultUtil.setData(compress);
        resultUtil.setStatus(200);
        return resultUtil;
    }

    /**
     * @author dxk
     * @date 2021/8/2 17:43
     
     * @return 
     * @throws 
     * @since 
    */
    @RequestMapping(value = "/spiderDisabledList/{pageNo}/{pageSize}")
    @ResponseBody
    public ResultUtil spiderDisabledList( @PathVariable Integer pageNo, @PathVariable Integer pageSize) {
		
        return null;
    }
}
